<template>
  <div class="dashboard-container">
    <div class="balance">
      <span style="padding-right:10px">
        当前账户余额:{{ amount }}
      </span>
      <el-button type="text" @click="dialogVisible = true">批量转账</el-button>
      <el-button type="text" @click="showCompany = true">对公转账</el-button>
      <el-dialog
        title="批量转账"
        :visible.sync="dialogVisible"
        width="80%"
      >
        <div>
          <div v-if="selectedFile == null">
            <input type="file" accept=".xlsx, .xls" @change="onFileChange">
            <a href="https://wechat.zhongshenglive.com/import.xlsx" download="导入发放">
              <el-button type="text">下载模板</el-button>
            </a>
          </div>
          <div v-else>
            <el-button size="mini" @click="reset">重新上传</el-button>
          </div>
          <div v-if="cards && cards.length > 0">
            <el-table
              :data="cards"
              style="width: 100%"
              :border="true"
            >
              <el-table-column
                prop="name"
                label="姓名"
                width="80px"
              />
              <el-table-column
                prop="idCard"
                label="身份证号"
              />
              <el-table-column
                prop="bankNo"
                label="银行卡号"
              />
              <el-table-column
                prop="phone"
                label="银行预留手机号"
              />
              <el-table-column
                prop="amount"
                label="汇款金额"
                width="100px"
              />
              <el-table-column
                label="银行卡检测"
                width="100px"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.status == 0">
                    <i class="el-icon-loading" />
                  </div>
                  <div v-if="scope.row.status == 1">
                    <el-tag type="success">可汇款</el-tag>
                  </div>
                  <div v-if="scope.row.status == -1">
                    <el-tag type="danger">不可汇款</el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="汇款状态"
                width="100px"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.status === 1">
                    <div v-if="scope.row.withdrawStatus == 0">
                      <i class="el-icon-loading" />
                    </div>
                    <div v-if="scope.row.withdrawStatus == 1">
                      <el-tag type="success">已完成</el-tag>
                    </div>
                    <div v-if="scope.row.withdrawStatus == -1">
                      <el-tag type="danger">汇款失败</el-tag>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-if="!canSend" type="primary" disabled>开 始 转 账</el-button>
          <el-button v-else type="primary" @click="widthdraw">开 始 转 账</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="请填写公户信息以及转账金额"
        :visible.sync="showCompany"
        width="40%"
      >
        <div>
          <el-form ref="form" label-width="80px">
            <el-form-item label="企业名称">
              <el-input v-model="companyData.companyName" />
            </el-form-item>
            <el-form-item label="营业执照">
              <el-input v-model="companyData.companyNo" />
            </el-form-item>
            <el-form-item label="开户银行">
              <el-select v-model="companyData.bankCode" filterable placeholder="请选择开户银行">
                <el-option
                  v-for="item in banks"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="银行卡号">
              <el-input v-model="companyData.bankNo" />
            </el-form-item>
            <el-form-item label="法人姓名">
              <el-input v-model="companyData.name" />
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="companyData.idCardNo" />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="companyData.phone" />
            </el-form-item>
            <el-form-item label="转账金额">
              <el-input-number v-model="companyData.amount" :min="1" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showCompany = false">取 消</el-button>
          <el-button type="primary" @click="companyWithdraw">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div>
      <div style="padding:10px;color:#909399">转账记录</div>
      <div>
        <el-row>
          <el-col :span="4"><div class="grid-content">
            <el-input v-model="name" placeholder="请输入姓名" />
          </div></el-col>
          <el-col :span="4"><div class="grid-content">
            <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="开始日期"
            />
          </div></el-col>
          <el-col :span="4"><div class="grid-content">
            <el-date-picker
              v-model="endDate"
              type="date"
              placeholder="结束日期"
            />
          </div></el-col>
          <el-col :span="4"><div class="grid-content">
            <el-select v-model="status" placeholder="请选择">
              <el-option
                v-for="item in withdrawStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div></el-col>
          <el-col :span="4"><div class="grid-content">
            <el-button icon="el-icon-search" circle @click="getWidthdraws" />
          </div></el-col>
        </el-row>
      </div>
      <div style="padding:10px">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            width="50"
          />
          <el-table-column
            label="日期"
          >
            <template slot-scope="scope">
              <div>
                {{ new Date(scope.row.createdTime) | dateFormat('YYYY-MM-DD HH:mm:ss') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            label="金额"
            width="180"
          />
          <el-table-column
            label="姓名"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.extraData && scope.row.extraData.card_info">
                {{ scope.row.extraData.card_info.card_name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="电话"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.extraData && scope.row.extraData.card_info">
                {{ scope.row.extraData.card_info.mp }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="银行卡"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.extraData && scope.row.extraData.card_info">
                {{ scope.row.extraData.card_info.card_no }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
          >
            <template slot-scope="scope">
              <div>
                {{ WITHDRAW_STATUS[scope.row.status] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="widthdrawAgin(scope.row)">再次转账</el-button>
                <el-button type="text" @click="downloadReceipt(scope.row)">电子回单</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        v-if="withdrawCard != ''"
        title="转账到银行卡"
        :visible.sync="showWithdraw"
        width="30%"
        @close="withdrawCard = ''"
      >
        <div>
          <div>账户：{{ withdrawCard.card_info.card_name }}</div>
          <div style="margin:10px 0px">转账银行卡：{{ withdrawCard.card_info.card_no }}</div>
          <div>
            <el-input v-model="withdrawAmount" placeholder="请输入转账金额" />
          </div>
          <div>
            最大可转账金额{{ amount }}
            <el-button type="text" @click="withdrawAmount = amount">全部转出</el-button>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showWithdraw = false">取 消</el-button>
          <el-button type="primary" @click="withdrawToCard">确 定 转 账</el-button>
        </span>
      </el-dialog>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalCount"
        :page-size="limit"
        @current-change="changePage"
        @prev-click="changePage"
        @next-click="changePage"
      />
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
  data() {
    return {
      selectedFile: null,
      amount: 0.00,
      dialogVisible: false,
      tableData: [],
      name: '',
      startDate: '',
      endDate: '',
      cards: [],
      canSend: false,
      limit: 20,
      loading: false,
      page: 1,
      totalCount: 0,
      WITHDRAW_STATUS: {
        'problems': '有问题',
        'suspicious': '可疑',
        'cancelled': '已取消',
        'scheduled': '延时提现',
        'rejected': '失败',
        'pending': '等待中',
        'accepted': '已通知渠道',
        'retrieved': '成功'
      },
      withdrawStatus: [
        {
          value: 'retrieved',
          label: '成功'
        },
        {
          value: 'rejected',
          label: '失败'
        }
      ],
      status: '',
      showWithdraw: false,
      withdrawCard: '',
      withdrawAmount: '',
      showCompany: false,
      companyData: {
        store: 1,
        amount: 1,
        companyName: '',
        companyNo: '',
        bankCode: '',
        bankNo: '',
        idCardNo: '',
        name: '',
        phone: ''
      },
      banks: [
        {
          value: '01040000',
          label: '中国银行'
        },
        {
          value: '01030000',
          label: '中国农业银行'
        },
        {
          value: '01020000',
          label: '中国工商银行'
        },
        {
          value: '01050000',
          label: '中国建设银行'
        },
        {
          value: '03010000',
          label: '交通银行'
        },
        {
          value: '04030000',
          label: '中国邮政储蓄银行'
        },
        {
          value: '03040000',
          label: '华夏银行'
        },
        {
          value: '03080000',
          label: '招商银行'
        },
        {
          value: '03100000',
          label: '上海浦东发展银行'
        },
        {
          value: '03160000',
          label: '浙商银行'
        },
        {
          value: '03060000',
          label: '广发银行'
        },
        {
          value: '03130012',
          label: '天津银行'
        },
        {
          value: '31346100',
          label: '济宁银行'
        },
        {
          value: '03050000',
          label: '中国民生银行'
        }
      ]
    }
  },
  created() {
    this.getBalance()
    this.getWidthdraws()
  },
  methods: {
    // 针对已经转账过的，再次单独转账
    widthdrawAgin(item) {
      console.log(item)
      this.withdrawCard = item.extraData
      this.showWithdraw = true
    },
    // 对公转账
    companyWithdraw() {
      console.log(this.companyData)
      if (this.companyData.companyName.trim() == '' || this.companyData.companyNo.trim() == '' || this.companyData.bank == '' || this.companyData.bankNo == '' || this.companyData.name == '' || this.companyData.idCardNo == '' || this.companyData.phone == '') {
        this.$message.error('请填写相关信息！')
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '数据交互中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const form = {
        card_no: this.companyData.bankNo,
        mp: this.companyData.phone,
        card_name: this.companyData.companyName,
        cert_no: this.companyData.idCardNo,
        bank_code: this.companyData.bankCode,
        card_type: 0,
        branch_name: '',
        branch_code: '103124075619',
        prov_id: '310000',
        area_id: '310100',
        band_code: '01030000',
        cert_type: '00',
        cert_validity_type: '0',
        cert_begin_date: '20200101',
        cert_end_date: '20360101',
        user: null
      }
      const company = {
        reg_name: this.companyData.companyName,
        license_code: this.companyData.companyNo,
        license_validity_type: 1,
        license_begin_date: '20200101',
        license_end_date: '20300101',
        reg_prov_id: '310000',
        reg_area_id: '310100',
        reg_district_id: '310101',
        reg_detail: '上海市徐汇区宜山路700号普天信息产业园2期C5栋',
        legal_name: this.companyData.name,
        legal_cert_type: '00',
        legal_cert_no: this.companyData.idCardNo,
        legal_cert_validity_type: 0,
        legal_cert_begin_date: '20200101',
        legal_cert_end_date: '20300101',
        contact_name: this.companyData.name,
        contact_mobile: this.companyData.phone
      }
      company['card_info'] = form
      console.log(company)
      this.axios.post(`/api/huifu-accounts/register/enterprise-user`, company)
        .then((res) => {
          console.log(123,res.data.cardInfo)
          const withdrawCard = {
            card_info: res.data.cardInfo,
            to_account: res.data.id
          }
          console.log(withdrawCard)
          this.withdrawCard = withdrawCard
          this.withdrawAmount = this.companyData.amount
          this.withdrawToCard()
        })
        .finally(() => {
          loading.close()
        })
    },
    // 下载回执
    downloadReceipt(item) {
      console.log(item)
      const loading = this.$loading({
        lock: true,
        text: '正在生成回单...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.get(`/api/huifu-accounts/${item.extraData.to_account}/get-receipt/${item.batchNo}`).then((res) => {
        console.log(res.data)
        window.open(`${res.data.viewPdfUrl}`)
        loading.close()
      })
    },
    getBalance() {
      this.axios.get(`/api/user`, { params: {
        '@expands': "['entity.balance']"
      }}).then((res) => {
        console.log(res.data)
        if (res.data.balance && res.data.balance.__metadata.amount) {
          this.amount = res.data.balance.__metadata.amount
        }
      })
    },
    getWidthdraws() {
      this.loading = true
      console.log(this.startDate, this.endDate)
      let startDate = ''
      let endDate = ''
      if (this.startDate !== '') {
        startDate = `${this.startDate.getFullYear()}/${this.startDate.getMonth() + 1}/${this.startDate.getDate()}`
      }
      if (this.endDate !== '') {
        endDate = `${this.endDate.getFullYear()}/${this.endDate.getMonth() + 1}/${this.endDate.getDate()}`
      }
      console.log(startDate, endDate)

      let filter = `entity.getId() > 0`
      if (startDate !== '') {
        filter += ` && entity.getCreatedTime() >= datetime.get('${startDate} 00:00:00')`
      }
      if (endDate !== '') {
        filter += ` && entity.getCreatedTime() <= datetime.get('${endDate} 23:59:59')`
      }
      if (this.status !== '') {
        filter += ` && entity.getStatus() == '${this.status}'`
      }
      this.axios.get(`/api/withdraws`, { params: {
        '@filter': filter,
        limit: this.limit,
        page: this.page,
        '@order': 'entity.id|DESC'
      }}).then((res) => {
        console.log('widthdraw', res)
        this.tableData = res.data
        this.totalCount = res.paginator.totalCount
        this.loading = false
      })
    },
    changePage(e) {
      console.log(e)
      this.page = e
      this.getWidthdraws()
    },
    onFileChange(e) {
      this.selectedFile = e.target.files[0]
      console.log(this.selectedFile)
      const fileName = this.selectedFile.name
      const fileExtension = fileName.split('.').pop().toLowerCase()
      const isExcel = ['xls', 'xlsx'].includes(fileExtension)
      if (!isExcel) {
        this.$message.error('请导入正确格式文件')
        return
      }
      // 读取文件
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })

        // 只处理第一个工作表
        const worksheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[worksheetName]

        // 将工作表转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

        // 整理数据
        console.log(jsonData)
        const title = jsonData[0]

        // 判断是否有数据
        if (jsonData.length <= 1) {
          this.$message.error('导入数据为空，请检查数据！')
          return
        }

        // 判断表头
        if (title[0] !== '姓名' || title[1] !== '身份证' || title[2] !== '银行卡' || title[3] !== '银行预留手机号' || title[4] !== '金额') {
          this.$message.error('导入文件表头错误，请按照模板表头填写后重试！')
          return
        }

        // 表头无问题之后，塞入银行卡数组
        const cards = []
        let amount = 0
        for (const i in jsonData) {
          if (i > 0 && jsonData[i].length === 5) {
            amount += parseFloat(jsonData[i][4])
            const card = {
              name: jsonData[i][0],
              idCard: jsonData[i][1].toString(),
              bankNo: jsonData[i][2].toString(),
              phone: jsonData[i][3].toString(),
              amount: parseFloat(jsonData[i][4]).toFixed(2),
              huifuAccount: '',
              withdrawStatus: -2,
              status: 0
            }
            cards.push(card)
          }
        }
        cards.push({
          name: '',
          idCard: '',
          phone: '合计:',
          amount: amount.toFixed(2)
        })
        this.cards = cards
        this.checkHuifuAccount()
      }
      reader.readAsArrayBuffer(this.selectedFile)
    },
    reset() {
      this.selectedFile = null
      this.cards = []
    },
    // 通过导入的银行卡数据，检查汇付钱包相关内容
    checkHuifuAccount() {
      const loading = this.$loading({
        lock: true,
        text: '正在检查银行卡信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.cards && this.cards.length > 0) {
        let count = this.cards.length - 1
        for (const i of this.cards) {
          if (i.bankNo) {
            const cardInfo = {
              card_no: i.bankNo,
              mp: i.phone,
              card_name: i.name,
              cert_no: i.idCard,
              card_type: 1,
              prov_id: '310000',
              area_id: '310100',
              band_code: '01030000',
              cert_type: '00',
              cert_validity_type: 0,
              cert_begin_date: '20150101',
              cert_end_date: '20350101'
            }
            const postData = {
              mobile_no: i.phone,
              card_info: cardInfo
            }
            console.log('数据', postData)
            this.axios.post(`/api/huifu-accounts/register/individual-user`, postData).then((res) => {
              console.log(res.data)
              i.huifuAccount = res.data.id
              i.status = 1
              count--
              if (count <= 0) {
                this.canSend = true
                console.log('已经操作完')
                loading.close()
              }
            }).catch(() => {
              i.status = -1
              count--
              if (count <= 0) {
                this.canSend = true
                loading.close()
                console.log('已经操作完')
              }
            })
          }
        }
      } else {
        this.$message.error('没有银行卡数据！')
      }
    },
    // 单独转账到一张单行卡
    withdrawToCard() {
      if (this.withdrawAmount <= 0) {
        this.$message.error('请输入转账金额')
        return
      }
      this.axios.get(`/api/balances`).then((res) => {
        if (res.data == null || parseFloat(res.data.amount) < this.withdrawAmount) {
          this.$message.error('账号余额不足！')
          return
        }
        this.$confirm(`一经转账将不能撤回，是否确定转账给【${this.withdrawCard.card_info.card_name}】？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const withdrawData = {
            payment: 'huifu',
            amount: this.withdrawAmount,
            extraData: {
              immediately: true,
              to_account: this.withdrawCard.to_account
            }
          }
          console.log(withdrawData)
          const loading = this.$loading({
            lock: true,
            text: '正在转账，请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios.post(`/api/withdraws`, withdrawData).then((res) => {
            loading.close()
            this.$message.success('转账成功，请留意银行卡信息！')
            this.withdrawCard = ''
            this.withdrawAmount = ''
            this.showWithdraw = false
            this.getBalance()
            this.getWidthdraws()
          })
        }).catch(() => {
          console.log('不做任何操作')
        })
      })
    },
    widthdraw() {
      this.canSend = false
      // 先计算一共需要转出几多，然后判断余额是否足够，不足够的，就不执行
      let totalAmount = 0
      for (const i of this.cards) {
        if (i.bankNo && i.bankNo !== '') {
          totalAmount += parseFloat(i.amount)
        }
      }
      this.axios.get(`/api/balances`).then((res) => {
        console.log('balancve', res.data, totalAmount)
        if (res.data == null || parseFloat(res.data.amount) < totalAmount) {
          this.$message.error('账号余额不足！')
          return
        }
        // 查主账号DM额度
        // this.axios.get(`/api/huifu-accounts/1/dm-amount-query`).then((res) => {
        // console.log('DM额度', res.data)
        // const dmAmount = res.data.dm_amt
        // if (totalAmount > parseFloat(dmAmount)) {
        //   this.$message.error(`商户可提现余额不足!`)
        //   return
        // }
        this.canSend = false
        this.$confirm('一经转账将不能撤回，是否确定按照列表内容进行转账？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 转账操作
          console.log('开始转账', this.cards)
          // const loading = this.$loading({
          //   lock: true,
          //   text: '正在执行转账操作...',
          //   spinner: 'el-icon-loading',
          //   background: 'rgba(0, 0, 0, 0.7)'
          // })
          this.postWidthdraw(0)
        }).catch(() => {
          console.log('不做任何操作')
        })
        // })
      })
    },
    // 操作提现，提现只能执行完一个再到下一个
    postWidthdraw(i) {
      const _this = this
      console.log(`执行第${i}次`, _this.cards[i], _this.cards[i].huifuAccount)
      if (_this.cards[i] && _this.cards[i].huifuAccount && _this.cards[i].huifuAccount > 1) {
        console.log('rulail ')
        _this.cards[i].withdrawStatus = 0
        const withdrawData = {
          payment: 'huifu',
          amount: _this.cards[i].amount,
          extraData: {
            immediately: true,
            to_account: _this.cards[i].huifuAccount
          }
        }
        // 傻逼汇付不能批量操作，执行完再操作都不行，只能强制停2秒再执行
        setTimeout(function() {
          // 执行提现操作
          _this.axios.post(`/api/withdraws`, withdrawData).then((res) => {
            _this.cards[i].withdrawStatus = 1
            if (i >= (_this.cards.length - 1)) {
              _this.canSend = true
              _this.$message.success('执行完毕，请查看相关内容')
              console.log('提现执行完毕')
            } else {
              _this.postWidthdraw(i + 1)
            }
          }).catch(() => {
            _this.cards[i].withdrawStatus = -1
            if (i >= (_this.cards.length - 1)) {
              _this.canSend = true
              _this.$message.success('执行完毕，请查看相关内容')
              _this.getWidthdraws()
              console.log('提现执行完毕')
            } else {
              _this.postWidthdraw(i + 1)
            }
          })
        }, 2000)
      } else {
        if (i >= (_this.cards.length - 1)) {
          _this.canSend = true
          _this.$message.success('执行完毕，请查看相关内容')
          _this.getWidthdraws()
          console.log('提现执行完毕')
        } else {
          _this.postWidthdraw(i + 1)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .balance{
    padding: 10px;
    color: #909399;
  }
  .grid-content{
    padding: 0px 10px;
  }
</style>
